package com.xq.tmall.agu.ferign;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xq.tmall.agu.core.agent.WebAgent;
import com.xq.tmall.agu.job.ITimerJob;
import com.xq.tmall.agu.task.EasyCrawl;
import com.xq.tmall.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component("IpValidSpider")
public class IpValidSpider implements Runnable {


    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private IpFerginUtil ipFerginUtil;

    @Override
    public void run() {
        log.info("IpValidSpider=======开始执行");
        try {
            LocalDateTime dateTime = LocalDateTime.now();
            // 周末不执行
           boolean isWeek = DateUtil.isWeekend(dateTime);
            if (dateTime.getHour() >= 15 && dateTime.getHour() < 17 && !isWeek) {
                boolean redisKey = redisTemplate.hasKey(RedisKey.PROXY_IP_KEY);
                if (redisKey) {
                    // 存在值，则判断是否失效
                    String valueKey = (String) redisTemplate.opsForValue().get(RedisKey.PROXY_IP_KEY);
                    String redisIp = valueKey.split(":")[0];
                    String redisPort = valueKey.split(":")[1];
                    log.info("redisIp:{}", redisIp);
                    boolean available = ProxyUtils.validateIp(redisIp, Integer.valueOf(redisPort), ProxyUtils.ProxyType.HTTP);
                    if (!available) {
                        available = ProxyUtils.validateIp(redisIp, Integer.valueOf(redisPort), ProxyUtils.ProxyType.HTTPS);
                    }
                    log.info("available:{}", available);
                    // 如果为true:有效不需要设置
                    if (!available) {
                        String result = new EasyCrawl<String>()
                                .webAgent(WebAgent.defaultAgent().useAgent(ipFerginUtil.getUseAgent()).url(ipFerginUtil.getIpUrl()))
                                .analyze(r -> r.getResult().getBody()).execute();
                        log.info("获取ip服务代理:" + result);
                        JSONObject jsonObject = JSON.parseObject(result);
                        JSONObject ipData = jsonObject.getJSONObject("data");
                        JSONArray jsonArray = ipData.getJSONArray("proxy_list");
                        String ipPort = jsonArray.getString(0);
                        String[] parts = ipPort.split(":");
                        String ip = parts[0];
                        String port = parts[1];
                        // 加到缓存中
                        ValueOperations<String, Object> valueOps = redisTemplate.opsForValue();
                        valueOps.set(RedisKey.PROXY_IP_KEY, ip.concat(":").concat(port));
                        redisTemplate.expire(RedisKey.PROXY_IP_KEY, 60, TimeUnit.MINUTES);
                    }
                } else {
                    String result = new EasyCrawl<String>()
                            .webAgent(WebAgent.defaultAgent().useAgent(ipFerginUtil.getUseAgent()).url(ipFerginUtil.getIpUrl()))
                            .analyze(r -> r.getResult().getBody()).execute();
                    log.info("获取ip服务代理:" + result);
                    JSONObject jsonObject = JSON.parseObject(result);
                    JSONObject ipData = jsonObject.getJSONObject("data");
                    JSONArray jsonArray = ipData.getJSONArray("proxy_list");
                    String ipPort = jsonArray.getString(0);
                    String[] parts = ipPort.split(":");
                    String ip = parts[0];
                    String port = parts[1];
                    // 加到缓存中
                    ValueOperations<String, Object> valueOps = redisTemplate.opsForValue();
                    valueOps.set(RedisKey.PROXY_IP_KEY, ip.concat(":").concat(port));
                    redisTemplate.expire(RedisKey.PROXY_IP_KEY, 60, TimeUnit.MINUTES);
                }
                // 每两分钟查询cookis
                String cookieUrl = "https://xueqiu.com/about/contact-us";

                // 将cookies设置到redis
                Map<Object, Object> hashEntries = redisTemplate.opsForHash().entries(RedisKey.PROXY_COOKIES);
                if (hashEntries.size() == 0) {
                    Map<String, String> cookies = WebAgent.getCookies(cookieUrl);
                    // 加到缓存中
                    redisTemplate.opsForHash().putAll(RedisKey.PROXY_COOKIES, cookies);
                    redisTemplate.expire(RedisKey.PROXY_COOKIES, 60, TimeUnit.MINUTES);
                }
            }else{
                ITimeJobFactory.getJob(ITimeJobFactory.TIMEJOB.IP_VALID).execute(ITimerJob.COMMAND.STOP);
            }
        } catch (Exception e) {
            log.info("ip校验异常:", e);
        }finally {
            try {
                ITimeJobFactory.getJob(ITimeJobFactory.TIMEJOB.IP_VALID).execute(ITimerJob.COMMAND.STOP);
            }catch (Exception e){
                log.info("关闭异常");
            }
        }
    }
}
